package com.badibadi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.badibadi.adapter.MyPolyAdapter;
import com.badibadi.fragment.MyPolyFragment;
import com.badibadi.fragment.MyPolyFragment1;
import com.badibadi.fragment.MyPolyFragment2;
import com.badibadi.fragment.MyPolyFragment3;
import com.badibadi.fragment.SeeClubPolyFragment;
import com.badibadi.infos.ImageAttribute;
import com.badibadi.infos.PhotoModel;
import com.badibadi.infos.Results;
import com.badibadi.logic.ImgFileListActivity;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;

/**
 * 看俱乐部的聚乐板 2014-9-30 my_poly_setting
 * 
 * @author Administrator @link UpPicture
 * 
 */
public class SeeClubPolyActivity extends BaseActivity {
	protected static final String TAG = "SeeClubPolyActivity";
	private PopupWindow poWindows;
	private boolean PopVisible = false;
	View root;
	List<PhotoModel> mList;
	private String uid;
	private String cid;
	private String club_type;// 3未加入俱乐部的人员
	private String is_apply;
	public SeeClubPolyFragment fragment0;
	// 版型 有三种 默认0 1参考 ， 2四个格子
	private String Version = "0";
	private FragmentManager manager;
	private AlertDialog builder;
	private Button record_linear_add_club, record_linear_quxiao;
	private Results resultsdd, resultsss;
	private ImageAttribute imageAttribute;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(SeeClubPolyActivity.this);
					Utils.showMessage(SeeClubPolyActivity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(SeeClubPolyActivity.this);
					Utils.showMessage(SeeClubPolyActivity.this,
							resultsdd.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				try {
					Utils.ExitPrgress(SeeClubPolyActivity.this);
					Utils.showMessage(SeeClubPolyActivity.this, getResources()
							.getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;

			case 4:
				Utils.ExitPrgress(SeeClubPolyActivity.this);
				Utils.showMessage(SeeClubPolyActivity.this, getResources()
						.getString(R.string.l_net_error));
				break;
			case 5:
				Utils.ExitPrgress(SeeClubPolyActivity.this);
				try {
					Utils.showMessage(SeeClubPolyActivity.this, getResources()
							.getString(R.string.l_xb147));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;

			case 6:
				Utils.ExitPrgress(SeeClubPolyActivity.this);
				Utils.showMessage(SeeClubPolyActivity.this, getResources()
						.getString(R.string.l_xa10));
				break;
			default:
				break;
			}
		}
	};
	/**
	 * 显示什么
	 */
	private int type = -1;// 0足迹，1梦想 2收藏 -1 全部

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		// android4Detail();
		setContentView(R.layout.activity_see_club_poly);
		// initInternet();
		try {
			uid = Utils.getUid(SeeClubPolyActivity.this);
			cid = getIntent().getStringExtra("cid");
			club_type = getIntent().getStringExtra("club_type");
			is_apply = getIntent().getStringExtra("is_apply");
		} catch (Exception e) {
			// TODO: handle exception
		}
		// cid = "11";
		if (cid == null) {
			cid = "-1";
		}

		init();
		Environment.getExternalStorageDirectory().toString();
		initFragment();
	}

	private void initFragment() {
		// TODO Auto-generated method stub
		LoadingFragment(0, uid, cid);
		// FragmentTransaction transaction=manager.beginTransaction();
		//
		// fragment0 = MyPolyFragment.getInstance();
		//
		// transaction.replace(R.id.my_poly1_layout, fragment0);
		// transaction.commit();
	}

	/**
	 * 读取到fragment
	 * 
	 * @param num
	 */
	private void LoadingFragment(int num, String uid, String fid) {
		FragmentTransaction transaction = manager.beginTransaction();
		fragment0 = SeeClubPolyFragment.getInstance();
		Bundle bun = new Bundle();
		bun.putString("uid", uid);
		bun.putString("cid", cid);
		// bun.putString("clu", club_type);
		bun.putString("is_apply", is_apply);
		fragment0.setArguments(bun);
		transaction.replace(R.id.my_poly1_layout, fragment0);
		transaction.commit();
	}

	private void init() {
		// TODO Auto-generated method stub
		manager = getSupportFragmentManager();
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						SeeClubPolyActivity.this.finish();
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 5 && resultCode == 5) {
			imageAttribute = (ImageAttribute) data
					.getSerializableExtra("img_info");
			imgInformationSave();
		}
	}

	private void imgInformationSave() {
		Utils.showPrgress(SeeClubPolyActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", "2");
				map.put("cid", cid);
				map.put("activity_id", 0);
				map.put("record_id", 0);
				map.put("record_article_id", 0);
				map.put("zhan_num", 0);
				try {
					map.put("img", fengzhuang_upimginfo());
				} catch (JSONException e) {
					   
				}
//				   ("上传图片发送参数是:" + map.toString());
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "photo/imgInformationSave");
				if (content != null) {
					resultsss = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("保存图片返回的结果是:" + content + " "
//							+ resultsss.getRetmsg());
					if (resultsss != null && !resultsss.equals("null")
							&& resultsss.isRet()) {
						handler.sendEmptyMessage(5);
					} else {
						handler.sendEmptyMessage(6);
					}
				} else {
					handler.sendEmptyMessage(4);
				}
			}
		});
	}

	public void OnClick(View view) {
		if (view.getId() == R.id.my_poly_setting) {
			if (!Utils.getUid(SeeClubPolyActivity.this).equals("")) {

			
			if (club_type != null && !club_type.equals("3")) {
				settingPopWindows();
				root.findViewById(R.id.my_poly1_uppicture).setOnClickListener(
						new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(
										SeeClubPolyActivity.this,
										ImgFileListActivity.class);
								intent.putExtra("panduan", "set");
								intent.putExtra("club", cid);
								startActivityForResult(intent, 5);
								poWindows.dismiss();
							}
						});
			} else {
				// Toast.makeText(getApplicationContext(), "请加入俱乐部", 0).show();
				builder = new Builder(SeeClubPolyActivity.this).setView(
						Back_Buju()).show();
			}} else {
				Utils.showMessage(SeeClubPolyActivity.this, getResources()
						.getString(R.string.l_xb10));
			}
		}
	}

	private JSONObject fengzhuang_upimginfo() throws JSONException {
		JSONObject object = new JSONObject();
		String s = "";
		if (imageAttribute.getService_img_address() != null
				&& !imageAttribute.getService_img_address().isEmpty()) {
			for (int i = 0; i < imageAttribute.getService_img_address().size(); i++) {
				s += imageAttribute.getService_img_address().get(i).toString();
			}
			//    ("______上传的图片地址是:" + s);
			object.put("path", s);
		}
		object.put("photoId", imageAttribute.getXiangceid());
		object.put("uid", Utils.getUid(SeeClubPolyActivity.this));
		object.put("title", getResources().getString(R.string.l_xb149));
		object.put("info", imageAttribute.getInfo());
		object.put("address", imageAttribute.getAbsolute_address());
		object.put("map_x", imageAttribute.getAddress_weidu());
		object.put("map_y", imageAttribute.getAddress_jingdu());
		object.put("participator", imageAttribute.getCanyu_persons());
		String t = "";
		if (imageAttribute.getBiaoqian_map() != null
				&& !imageAttribute.getBiaoqian_map().isEmpty()) {
			//    ("数" + imageAttribute.getBiaoqian_num());
			for (int j = 0; j < imageAttribute.getBiaoqian_num(); j++) {
				if (imageAttribute.getBiaoqian_map().get(j) != null) {
					t += imageAttribute.getBiaoqian_map().get(j) + ",";
				}
			}
			object.put("typeid", quchu_zuihou(t));
		}
		object.put("attachment", imageAttribute.getLaiyuan());
		object.put("is_show", imageAttribute.getIs_displaydongtai());
		return object;
	}

	private String quchu_zuihou(String s) {
		return s.substring(0, s.length() - 1);
	}

	private View Back_Buju() {
		View view = null;
		LayoutInflater inflater = LayoutInflater.from(SeeClubPolyActivity.this);
		view = inflater.inflate(R.layout.recordlistclub_is_add_club, null);
		record_linear_add_club = (Button) view
				.findViewById(R.id.record_linear_add_club);
		record_linear_quxiao = (Button) view
				.findViewById(R.id.record_linear_quxiao);
		TextView infos = (TextView) view.findViewById(R.id.infos);
		infos.setText("才能在此俱乐部上传图片");
		record_linear_add_club.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), "加入", 0).show();
				if (is_apply.equals("0")) {
					Add_club("0", "");
				} else {
					Intent intent = new Intent(SeeClubPolyActivity.this,
							AddApplyFormActivity.class);
					intent.putExtra("pan", "set");
					intent.putExtra("cid", cid);
					startActivity(intent);
				}
				builder.dismiss();
			}
		});
		record_linear_quxiao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// Toast.makeText(getApplicationContext(), "取消", 0).show();
				builder.dismiss();
			}
		});
		return view;
	}

	private void Add_club(final String is_apply, final String content) {
		Utils.showPrgress(SeeClubPolyActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(SeeClubPolyActivity.this));
				map.put("cid", cid);
				map.put("is_apply", is_apply);
				if (is_apply.equals("1")) {
					map.put("contents", content);
				}
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "club/attendClub");
				if (content != null) {
					resultsdd = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("加入俱乐部返回的参数是:" + content + " "
//							+ resultsdd.getRetmsg());
					if (resultsdd != null
							&& !resultsdd.getRetmsg().equals("null")) {
						handler.sendEmptyMessage(2);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 加载一个悬浮对话框 有上传图片
	 */
	private void settingPopWindows() {// MyPoly1Activity
		// TODO Auto-generated method stub
		root = this.getLayoutInflater().inflate(
				R.layout.see_club_poly_popwindows, null);
		float width = getScreenSize(SCREENW);
		float height = (getScreenSize(SCREENH)) * 2 / 5;
		root.findViewById(R.id.my_poly1_popwin_close).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						poWindows.dismiss();
					}
				});
		root.findViewById(R.id.create_new_poly).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(SeeClubPolyActivity.this,
								ClubSpacePolyActivity.class);
						intent.putExtra("cid", cid);
						startActivity(intent);
						poWindows.dismiss();
					}
				});

		int dp80_px = DisplayUtil.dip2px(SeeClubPolyActivity.this, 80);
		int dp50_px = DisplayUtil.dip2px(SeeClubPolyActivity.this, 50);
		int dp300_px = DisplayUtil.dip2px(SeeClubPolyActivity.this, 300);
		poWindows = new PopupWindow(root, (int) width, (int) height);
		poWindows.setBackgroundDrawable(new BitmapDrawable());
		// poWindows.setWidth(LayoutParams.WRAP_CONTENT);
		poWindows.setHeight(LayoutParams.WRAP_CONTENT);
		poWindows.setFocusable(true);
		poWindows.setTouchable(true);
		poWindows.setOutsideTouchable(true);
		poWindows.showAtLocation(findViewById(R.id.my_poly1_layout),
				Gravity.BOTTOM, 0, 0);
		PopVisible = true;

	}

}
